﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.WowAddonStudio.FrameXml.Components.Descriptors.Filters;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Descriptors
{
    public class PropertyDescriptorFilterManager
    {
        private readonly List<PropertyDescriptorFilter> filters;

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyDescriptorFilterManager"/> class.
        /// </summary>
        public PropertyDescriptorFilterManager()
        {
            filters = new List<PropertyDescriptorFilter>(4);
        }

        /// <summary>
        /// Adds the specified filter.
        /// </summary>
        public void Add<TPropertyDescriptorFilter>() where TPropertyDescriptorFilter : PropertyDescriptorFilter, new()
        {
            filters.Add(new TPropertyDescriptorFilter());
        }

        /// <summary>
        /// Clears this instance.
        /// </summary>
        public void Clear()
        {
            filters.Clear();
        }

        /// <summary>
        /// Filters the specified control.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyDescriptor">The property descriptor.</param>
        /// <returns></returns>
        public PropertyDescriptor Filter(object instance, PropertyDescriptor propertyDescriptor)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (propertyDescriptor == null) 
                throw new ArgumentNullException("propertyDescriptor");

            foreach (var filter in filters)
            {
                propertyDescriptor = filter.Filter(instance, propertyDescriptor);
                if (propertyDescriptor == null)
                    break;
            }

            return propertyDescriptor;
        }
    }
}
